package db

import (
	"database/sql"
	"errors"
	"gin-api-server/app/model/fs"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	"gin-api-server/core_library/global"
)

var SqlDb *sql.DB

func InitMysql() error {

	dsn := global.Config.DataBase.User + ":" + global.Config.DataBase.Password + "@tcp(" + global.Config.DataBase.Host + ":" + global.Config.DataBase.Port + ")/" + global.Config.DataBase.Dbname + "?charset=" + global.Config.DataBase.Charset + "&parseTime=True&loc=Local"

	logLevel := logger.Silent
	if global.Config.Server.Debug {
		logLevel = logger.Info
	}
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             5 * time.Second, // 慢 SQL 阈值
			LogLevel:                  logLevel,        // 日志级别
			IgnoreRecordNotFoundError: true,            // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,           // 禁用彩色打印
		},
	)

	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:               dsn,
		DefaultStringSize: 256,
	}), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		PrepareStmt:            true,
		SkipDefaultTransaction: true,
	})

	if err != nil {
		return errors.New("链接数据库失败: " + err.Error())
	}

	sqlDB, err := db.DB()
	if err != nil {
		return errors.New("链接数据库失败: connect db server failed")
	}
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(1000)
	sqlDB.SetConnMaxLifetime(time.Second * 600)

	global.DB = db
	fs.Model = db
	SqlDb = sqlDB
	return nil
}
